package com.android.nextBus.JSON;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.nextBus.DB.StopItem;

public class RouteParser {
	
	/**
	 * Parses the array of stop items returned from the server's route service
	 * into a list of StopItem objects
	 * @param jsonArray the array returned from the Route Service
	 * @return a list of Stop Items
	 */
	public static List<StopItem> parse(String data) {
		
		List<StopItem> stops = new ArrayList<StopItem>();
		try {
			JSONArray jsonArray = new JSONArray(data);
			
			for (int i = 0; i < jsonArray.length(); ++i) {
				JSONObject obj = (JSONObject) jsonArray.get(i);
				int stopID = obj.getInt("i");
				//int stopID = i;
				
				int lon = obj.getInt("x");		// note: the server returns lat/lon as integers, 
				int lat = obj.getInt("y");		// already converted for GeoPoint use
				String desc = obj.getString("d");
				String name = obj.getString("n");
					
				stops.add(new StopItem(name, desc, lon, lat, stopID));
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		return stops;
	}
}
